<template>
  <header class="w-full p-1 flex flex-col items-center">
    <div class="w-full flex flex-row gap-2 justify-between items-center p-1">
      <n-input class="rounded-6px w-full text-12px h-[28px]" placeholder="搜索" v-model:value="SearchKeyWord">
        <template #prefix>
          <component :is="RenderIcon(SearchOutline)" />
        </template>
      </n-input>

      <n-popover
        :show-arrow="false"
        style="background-color: var(--bg-input); color: white; padding: 5px"
        trigger="click"
      >
        <template #trigger>
          <n-button size="small" style="padding: 0 5px; background-color: var(--bg-input)">
            <template #icon>
              <component :is="RenderIcon(Add)" />
            </template>
          </n-button>
        </template>
        <div>
          <p class="addMoreItem" @click="ShowModal = true">
            <component :is="RenderIcon(AddCircleOutline, 'text-fontPrimary text-base')" />
            创建群聊
          </p>
          <p class="addMoreItem" @click="OpenFriendAdd">
            <component :is="RenderIcon(PersonAddOutline, 'text-fontPrimary text-base')" />
            添加好友
          </p>
        </div>
      </n-popover>
    </div>
  </header>
  <n-modal
    v-model:show="ShowModal"
    :loading="loading"
    class="rounded-8px"
    transform-origin="center"
    :on-after-enter="GetFriendList"
    :auto-focus="false"
  >
    <GroupTransfer :list="CandidateFriendList" @cancel="ShowModal = false" @confirm="ConformTransFormer" />
  </n-modal>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { IUser } from "@/types/user";
import { ICandidateFriendListItem } from "@/types/friend";
import { ChatType, MessageType } from "@/types/chat";
import { useChat } from "@/store/modules/chat";
import { useSession } from "@/store/modules/session.ts";
import { useRoute, useRouter } from "vue-router";
import { RequestFriendList } from "@/api/friend";
import { CreateGroup } from "@/api/group";
import { RenderIcon } from "@/utils/common.ts";
import { ElMessage } from "element-plus";
import { NButton, NInput, NModal, NPopover } from "naive-ui";
import { Add, AddCircleOutline, PersonAddOutline, SearchOutline } from "@vicons/ionicons5";
import GroupTransfer from "@/components/GroupTransfer/index.vue";
import { useUser } from "@/store/modules/user";
import { useCache } from "@/store/modules/cache";
const user = useUser();
const route = useRoute();
const router = useRouter();
const chat = useChat();
const session = useSession();
const cache = useCache();
const SearchKeyWord = defineModel<string>("searchKeyWord");
let loading = ref(false);
let ShowModal = ref(false);
let FriendList = ref<IUser[]>();
// 好友选择列表
const CandidateFriendList = computed((): ICandidateFriendListItem[] => {
  if (!FriendList.value) return [];
  return (
    FriendList.value.map((item) => ({
      id: item.id,
      name: item.name!,
      avatar: item.avatar!,
      select: false,
    })) || []
  );
});

// 打开好友添加页面
function OpenFriendAdd() {
  window.electronApi.createWindow({
    title: "addFriend",
    path: "addFriend",
    width: 700,
    height: 600,
  });
}

// 确认建群
async function ConformTransFormer(list: number[]) {
  loading.value = true;
  const res: any = await CreateGroup(list);
  loading.value = false;
  if (res.status !== 200) return;
  cache.AddGroupListCache(res.data);
  const { id: groupId, sessionId, name, avatar } = res.data;
  let commonParams = { name, avatar, sessionId, chatType: ChatType.group };
  session.AddSession({
    ownerId: user.userId!,
    toId: groupId,
    sessionType: MessageType.text,
    content: "",
    unread: 0,
    ...commonParams,
  });
  chat.ChatObject = { id: groupId, ...commonParams };
  ShowModal.value = false;
  ElMessage.success("创建成功");
  if (route.path != "/message") await router.push("/message");
}

// 获取好友列表
async function GetFriendList() {
  let res = await RequestFriendList();
  if (res.status != 200 || !res.data) return;
  FriendList.value = res.data;
}
</script>

<style lang="scss" scoped>
:deep(.el-input__wrapper) {
  background-color: var(--window-bg) !important;
  border-color: transparent !important;
}

.addMoreItem {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 5px;
  color: var(--font-primary);
  cursor: pointer;

  &:hover {
    background-color: var(--bg-center-hover);
  }
}
</style>
